/* 
 * @Author: panqian
 * @Date:   2017-06-20 13:38:28
 * @Last Modified by:   anchen
 * @Last Modified time: 2017-06-23 14:35:54
 */

/*
应急响应球界面的实现
 * */

namespace('n2.yingji');

n2.yingji = function() {
	this._viwer = null;
	this._camera = null;
	this._handler = null;
	this._scene = null;
	n2.base(this, n2.main);
};

n2.definePrototype(n2.yingji.prototype, {
	viewer: {
		get: function() {
			return this._viewer;
		},
		set: function(value) {
			this._viewer = value;
		}
	},
	handler: {
		get: function() {
			return this._handler;
		},
		set: function(value) {
			this._handler = value;
		}
	},
	camera: {
		get: function() {
			return this._camera;
		},
		set: function(value) {
			this._camera = value;
		}
	},
	scene: {
		get: function() {
			return this._scene;
		},
		set: function(value) {
			this._scene = value;
		}
	}
});

n2.yingji.prototype.init = function() {
	var self = this;
	var viewer = self.viewer = n2.viewer;
	var scene = viewer.scene;
	var camera = viewer.camera;
	var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
	var datas = null;
	//搜索
	var searchInp = document.querySelector("#searchInp");
	var claerVal = document.querySelector("#claerVal");
	var img_yj = document.querySelector("#img_yj");
	img_yj.innerHTML = '<img src="images/legend.png" class="img-responsive">';
	//   左侧展示列表
	var contentBox = document.getElementById("response"); //列表的展示盒子
	self.primitive = null;
	
	//画出所有应急响应点位
	n2.ajax.post('http://' + n2.YingjiC, {
		"kind_code": "01",
	}, "json").then(function(data) {
		var res = JSON.parse(data);
		datas = res;
		//filterdata(res);

		//搜索功能
		searchInp.oninput = function() {
			var val = this.value;
			if(val.length != 0) {
				claerVal.className = "";
			} else {
				claerVal.className = "disnone";
			}
			disasterSearch(datas, val);
		}

		claerVal.addEventListener("tap", function() {
			searchInp.value = "";
			claerVal.className = "disnone";
			disasterSearch();
			searchInp.blur();
		})

		//左侧滑信息列表
		renderer(res);
		
		//点位图好   --------------   第三条数据开始没有location参数   无法确定位置   不能进行画点
		var scene = viewer.scene;
		var billboards = scene.primitives.add(new Cesium.BillboardCollection());

		for(var p = 0; p < res.length; p++) {
			var res = res[p]["data"];
			console.log(res);
			//经纬度一样时 不显示报错
			var longitude = res["lon"];
			var latitude = res["lat"];
			console.log(longitude, latitude, p);
			var height = 1000;
			//灾种
			var t = res["disaster"];
			var url = null;
			var responeLevel = res["respone_level"];//等待应急参数的确认，目前没有
//			var responeLevel = 2;
			//灾种不同，显示的点位图标不同
			if(t == '地震') {
				url = './images/earthquake' + responeLevel + '.png';
			} else if(t == '旱灾') {
				url = './images/gan' + responeLevel + '.png';
			} else if(t == '台风') {
				url = './images/tai' + responeLevel + '.png';
			}

			billboards.add({
				position: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
				image: url,
				id: res["id"],
				width: 6 * responeLevel,
				height: 9 * responeLevel
			})
		}

	})

	//左键单击地震点显示地震详细信息 
	handler.setInputAction(function(event) {
		//      var scene = viewer.scene;
		var o = viewer.scene.pick(event.position);
		console.log(o); //获取点击的最上方的元素
		if(o === undefined) {
			if(self.primitive != null) {
				scene.primitives.remove(self.primitive)
			}
			return;
		}

		if(typeof(o.id) === 'string') {
			var num = (o.id).indexOf('s');
			if(num === -1) {
				if(self.primitive != null) {
					scene.primitives.remove(self.primitive)
				}
				if(n2.defined(o)) {
					n2.ajax.post('http://' + n2.billId, {
						"kind_code": "01",
						"product_code": "0001", //接口还没写好
						"id": o.id
					}, 'json').then(function(res) {
						//				console.log(res)
						var priID = o.id;
						var resBill = JSON.parse(res);
						console.log(priID, res)
						draw(resBill, priID);
					})
				}
			} else {
				console.log(2)
				var leng = (o.id).length;

				var newId = (o.id).substr(0, leng - 1);
				// console.log(plus.webview.getWebviewById('yingjixiangyingzhuanti.html'));
				//获得详情页面
				//			if(!detailPage2) {
				//			detailPage2 = plus.webview.getWebviewById('yingjixiangyingzhuanti.html');
				//			}
				//触发详情页面的newsId事件
				// mui.fire(detailPage2, 'newsId2', {
				// 	id: newId
				// });

				//打开详情页面          
				mui.openWindow({
					url: 'yingjixiangyingzhuanti.html',
					id: 'yingjixiangyingzhuanti.html',
					show: {
						autoShow: true, //页面loaded事件发生后自动显示，默认为true
						aniShow: 'pop-in',
						duration: '100',
					},
                    createNew:true,
                    extras: {
                        id:newId
                    },
					styles: {
						popGesture: 'none',
						hardwareAccelerated: true
					},
					waiting: {
						autoShow: true
					}
				});
			}
		}
		//等数据id的更新
		draw(datas, o.id);
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	//球上的信息展示
	function draw(res, id, bool) {
		var data = null;
		bool = bool || false;
		//没必要的筛选，因数据结构及接口问题
		if(bool) {
			data = res;
		} else {
			for(var i = 0; i < res.length; i++) {
				if(res[i]["data"]["id"] == id) {
					data = res[i]["data"];
					break;
				}
			}
		}
		console.log(data);
		var canvas = document.createElement("canvas");
		canvas.width = 290; //260
		canvas.height = 310; //
		var ctx = canvas.getContext("2d");
		if(data == null){
			return;
		};
		var longitude1 = data.lon;
		var latitude1 = data.lat;
		var height = 0;
		var title = "国家" + data.rank + "级救灾应急响应："; //标题
		var name = data.name;
		var happenTime = "响应时间：" + data.happenTime; //响应时间需要加数据
		//出发时间
		var goTime = "出发时间：" + data.goTime;
		//返回时间
		var backTime = "返回时间：" + data.backTime;
		//参与成员
		var groupMembers = "工作组成员：" + data.groupMembers;
		//批准人
		var responser = "批准人：" + data.responser;

		var image = new Image();
		image.src = './images/billboard8.png'; //语言框
		var devicePixelRatio = window.devicePixelRatio || 1,
			backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1,
			ratio = devicePixelRatio / backingStoreRatio;

		var oldWidth = 290;
		var oldHeight = 310;
		canvas.width = oldWidth * ratio;
		canvas.height = oldHeight * ratio;
		canvas.style.width = oldWidth + 'px';
		canvas.style.height = oldHeight + 'px';
		ctx.scale(ratio, ratio);

		image.onload = function() {
			ctx.drawImage(image, 0, 0);
			//标题
			ctx.lineWidth = 1;
			ctx.font = "14px Modern"; //Microsoft YaHei UI
			ctx.fontWeight = "bold";
			ctx.strokeStyle = "#000066";
			//var titleLen = title.length;
			//我们的容器最多放两行文字
			/*if(titleLen <= 18) {
				ctx.strokeText(title, 8, 22);
			} else if(titleLen > 18 && titleLen <= 35) {
				ctx.strokeText(title.substr(0, 19), 8, 18);
				ctx.strokeText(title.substr(19), 8, 35);
			} else if(titleLen > 35) {
				ctx.strokeText(title.substr(0, 19), 8, 18);
				ctx.strokeText(title.substr(19, 20) + '...', 8, 35);
			}*/
			//标题及名称
			ctx.strokeText(title, 10, 22);
			ctx.strokeText(name, 10, 37);
			//内容
			ctx.font = "12px Modern"; //Microsoft YaHei UI
			ctx.strokeStyle = "#3C3C3C";
			//响应时间
			ctx.strokeText(happenTime, 10, 55);
			//审批人员
			ctx.strokeText(responser, 10, 73);
			//参与人员
			ctx.strokeText(groupMembers, 10, 91);
			//出发时间
			ctx.strokeText(goTime, 10, 109);
			//返回时间
			ctx.strokeText(backTime, 10, 127);
			var imgBaes64 = canvas.toDataURL("image/png");
			var img = new Image();
			img.src = imgBaes64;
			img.onload = function() {
				//console.log(img)
				self.primitive = scene.primitives.add(new Cesium.BillboardCollection());
				self.primitive.add({
					position: Cesium.Cartesian3.fromDegrees(longitude1, latitude1, 20000),
					image: img,
					horizontalOrigin: Cesium.HorizontalOrigin.Center,
					pixelOffset: new Cesium.Cartesian2(0, 0),
					pixelOffsetScaleByDistance: new Cesium.NearFarScalar(1.5e2, 3.0, 1.5e7, 0),
					width: 290,
					height: 308,
					id: id + 's',
				})
			}
		};

		image.style.width = '290px';
		image.style.height = '308px';
		image.style.backgroundRepeat = "no-repeat";
		image.style.backgroundPosition = "center";
		// 获取当前视角高度=====方法1
		//var scene = viewer.scene;
		//var ellipsoid = scene.globe.ellipsoid;
		//var height=ellipsoid.cartesianToCartographic(viewer.camera.position).height;
		//获取当前视角的高度    ======= 方法2                            
		var height1 = camera.position;
		var height2 = Cesium.Cartographic.fromCartesian(height1).height;
		camera.flyTo({
			destination: Cesium.Cartesian3.fromDegrees(longitude1, latitude1, height2),
			duration: 1
		})
	}
	//筛选功能
	var filterdata = function() {
		//监控选择项
		var cd_dropdown = document.querySelector("#cd-dropdown");
		var asidedate = document.querySelector("#asidedate");

		var cdval = "全部",
			asval = '1900-01-01 00:00:00',
			endtime = getNowFormatDate();
		//筛选灾害事件  		res[i].disaster;
		cd_dropdown.onchange = function() {
			cdval = cd_dropdown.value;
			console.log(cdval);
			//灾害筛选
			if(cdval == "全部") {
				var disasterAll1 = document.querySelectorAll("[data-disaster]");
				for(var i = 0; i < disasterAll1.length; i++) {
//					disasterAll1[i].className = "mui-table-view-cell";
				}
			} else {
				var disasterAll2 = document.querySelectorAll("[data-disaster]")
				for(var i = 0; i < disasterAll2.length; i++) {
//					disasterAll2[i].className = "mui-table-view-cell";
					if(disasterAll2[i].getAttribute("data-disaster") != cdval) {
//						disasterAll2[i].className = "mui-table-view-cell disnone";
disasterAll2[i].className = "disnone";
					}
				}
			}
		};
		//时间筛选	年份		res[i].responseStartTime.substr(0, 4)
		asidedate.onchange = function() {
			asval = asidedate.value + " 00:00:00";
			console.log(asval);
		}

		var filterclick = document.querySelector("#filterclick");
		filterclick.addEventListener("tap", function(e) {
	
		})
	}

	filterdata();

	//左侧列表信息展示
	function renderer(data) {
		contentBox.innerHTML = '';
		for(var i = 0; i < data.length; i++) {
			var res = data[i]["data"];
			var t = res["disaster"];
			var litxt = document.createElement('li');
//			litxt.className = 'mui-table-view-cell';
			litxt.title = res["id"];
			litxt.className = "litxt";
			litxt.setAttribute('data-disaster', t);
			//				litxt.setAttribute('data-year', res["backTime"]);

			var atxt = document.createElement('a');
			litxt.appendChild(atxt);

			//图标
			var imgtxt = document.createElement('img');
			imgtxt.className = 'mui-media-object mui-pull-left';
			var urltxt = null;

			//灾种不同，显示的点位图标不同
			if(t == '地震') {
				urltxt = './images/DZ@3x.png';
			} else if(t == '洪涝') {
				urltxt = './images/HL@3x.png';
			} else if(t == '旱灾') {
				urltxt = './images/GH@3x.png';
			} else if(t == '台风') {
				urltxt = './images/TF@3x.png';
			}

			imgtxt.src = urltxt;
			atxt.appendChild(imgtxt);
			var divtxt = document.createElement('div');
			divtxt.className = 'mui-media-body';
			atxt.appendChild(divtxt);

			var p1 = document.createElement('p');
			p1.className = 'mui-ellipsis';
			p1.innerHTML = res.name;
			divtxt.appendChild(p1);

			var p2 = document.createElement('p');
			p2.innerHTML = res["happenTime"];
			divtxt.appendChild(p2);

			var span = document.createElement('span');
			span.className = 'mui-icon mui-icon-info spanClick';
			divtxt.appendChild(span);

			contentBox.appendChild(litxt);

			//为li标签绑定响应的事件，表球联动
			litxt.addEventListener('tap', function(event) {
				var id = this.title;
				console.log(res, id);
				mui('.zuocehua').offCanvas('close');
				draw(res, id, true);
			}, false);

			span.addEventListener('tap', function(event) {
				var newId = this.title;
				//打开详情页面          
				mui.openWindow({
					url: 'yingjixiangyingzhuanti.html',
					id: 'yingjixiangyingzhuanti.html',
					show: {
						autoShow: true, //页面loaded事件发生后自动显示，默认为true
						aniShow: 'pop-in',
						duration: '100',
					},
                    createNew:true,
                    extras: {
                        id:newId
                    },
					styles: {
						popGesture: 'none',
						hardwareAccelerated: true
					},
					waiting: {
						autoShow: true
					}
				});
			}, false);
		}
	}
	
	//搜索创建展示列表
	function disasterSearch(res, val) {
		var datas = res || [];
		var box = document.querySelector("#headerBox")
		//获取内容并判断s
		var val = val || ""; //文本框中的内容
		//从datas里面寻找和val匹配的项目 如果匹配放到一个新数组中
		var filterArr = [];
		for(var i = 0; i < datas.length; i++) {
			var data = datas[i]["data"]["name"];
			if(data.indexOf(val) >= 0) {
				filterArr.push(datas[i]["data"]);
			}
		}
		console.log(filterArr);

		//1.div会重叠
		//在创建div之前 先判断一下有没有 如果有要先把之前的div删除
		var popDiv = document.getElementById("pop");
		//如果有 就是对象 如果没有就是null
		if(popDiv) {
			//如果能进来 说明已经有了 如果有了就要删除
			box.removeChild(popDiv);
		}
		//2.如果没有匹配项 就不创建了
		if(filterArr.length === 0) {
			return;
		}
		//3.如果用户输入为空 也不创建了
		if(val === "") {
			return;
		}
		//动态生成结构
		popDiv = document.createElement("div");
		popDiv.id = "pop";
		box.appendChild(popDiv);
		var ul = document.createElement("ul");
		popDiv.appendChild(ul);
		//根据filterArr里的数据 创建li 并追加到ul中
		for(var i = 0; i < filterArr.length; i++) {
			var title = filterArr[i]["name"]; //名称
			var time = "应急响应时间：" + filterArr[i]["happenTime"]; //时间 
			var li = document.createElement("li");
			console.log(res,i)
			console.log(res[i]["data"].id);
			li.title = res[i]["data"].id || "";
			var h4 = document.createElement("h4");
			var p = document.createElement("p");
			h4.innerText = title;
			p.innerText = time; //处理一下兼容问题
			li.appendChild(h4);
			li.appendChild(p);
			ul.appendChild(li);
			li.addEventListener('tap', function(event) {
				draw(datas,this.title);
				searchInp.blur();
				searchInp.value = "";
				claerVal.className = "disnone";
				box.removeChild(popDiv);
			}, false);
		}
	}
}